<?php defined('_VALID_MOS') or die('Direct Access to this location is not allowed.');

/*
 * Copyright Copyright (C) 2007 Alain Georgette. All rights reserved.
 * Copyright Copyright (C) 2006 Frantisek Hliva. All rights reserved.
 * License http://www.gnu.org/copyleft/gpl.html GNU/GPL, see LICENSE.php
 *
 * !JoomlaComment is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * !JoomlaComment is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
 * MA  02110-1301, USA.
 */

require_once('utils.php');
require_once('strutils.php');
require_once('jscript.php');
require_once('security.php');

/* TODO: use public function for copied functions....
 */
class template {
    var $_live_site;
    var $_absolute_path;
    var $_template_path = '';
    var $_name = '';
    var $_title = '';
    var $_post = '';
    var $_search = '';
    var $_searchResults = '';
    var $_form = '';

    function template($name)
    {
        $this->_name = $name;
    }

    function loadFromFile()
    {
        $fileName = $this->_absolute_path .'/templates/'. $this->_name . '/index.html';
        if (file_exists($fileName)) {
            $file = fopen ($fileName, 'r');
            $template = fread ($file, filesize($fileName));
            fclose($file);
            return $template;
        } else die ('!JoomlaComment template not found: ' . $this->_name);
    }

    function CSS()
    {  
        return insertToHead('<link rel="stylesheet" href="' . $this->_live_site . '/templates/' . $this->_name . '/css/template_css.css" type="text/css" />');
    }

    function parse()
    {
        $template = $this->loadFromFile();
        $this->_menu = block($template, 'menu');
        $this->_search = block($template, 'search');
        $this->_searchResults = block($template, 'searchresults');
        $this->_post = block($template, 'post');
        $this->_form = block($template, 'form');
    }
}

class properties extends template {
    var $_ajax;
	var $_local_charset;	
    var $_only_registered;
    var $_language;
    var $_moderator = array();
    var $_exclude_sections = array();
    var $_exclude_categories = array();
    var $_template;
    var $_emoticon_pack;
    var $_tree;
    var $_tree_indent;
    var $_sort_downward;
    var $_support_emoticons;
    var $_support_UBBcode;
    var $_support_pictures;
    var $_censorship_enable;
    var $_censorship_case_sensitive;
    var $_censorship_words;
    var $_censorship_usertypes;
    var $_IP_visible;
    var $_IP_partial;
    var $_IP_caption;
    var $_IP_usertypes;
    var $_preview_visible;
    var $_preview_length;
    var $_preview_lines;
    var $_voting_visible;
    var $_use_name;
    var $_notify_admin;
    var $_notify_email;
    var $_notify_users;
    var $_rss;
    var $_date_format;
    var $_captcha;
    var $_autopublish;
    var $_ban;
    var $_avatar;
    var $_profile;
    var $_profiles;
    var $_maxlength_text;
    var $_maxlength_word;
    var $_show_readon;
    var $_xmlerroralert;

    function properties($absolutePath, $liveSite, $sectionId, $categoryId, &$exclude)
    {
        global $my, $mosConfig_absolute_path;

		//require("$absolutePath/../config.comment.php"); 
		/* abolutepath = .../administrator/components/com_comment/joscomment absolute path */
		require_once("$mosConfig_absolute_path/administrator/components/com_comment/class.config.comment.php");
		$config = new config();
		$config->load(); 
		      
        $this->_ajax = $config->_ajax;
        $this->_local_charset = $config->_local_charset;
        $this->_only_registered = $config->_only_registered;
        $this->_language = $config->_language;
        $this->_moderator = explode(',', $config->_moderator);
        $this->_exclude_sections = explode(',', $config->_exclude_sections);
        if ($exclude && in_array((($sectionId == 0) ? -1 : $sectionId), $this->_exclude_sections)) {
            $exclude = true;
            return;
        }
        $this->_exclude_categories = explode(',', $config->_exclude_categories);
        if ($exclude && in_array($categoryId, $this->_exclude_categories)) {
            $exclude = true;
            return;
        }
        $this->_template = $config->_template;
        $this->_emoticon_pack = $config->_emoticon_pack;
        $this->_emoticon_wcount = $config->_emoticon_wcount;
        $this->_tree = $config->_tree;
        $this->_tree_indent = $config->_tree_indent;
        $this->_sort_downward = ($this->_tree ? 0 : $config->_sort_downward);
        $this->_support_emoticons = $config->_support_emoticons;
        $this->_support_UBBcode = $config->_support_UBBcode;
	$this->_support_pictures = $config->_support_pictures;
        $this->_censorship_enable = $config->_censorship_enable && in_array(intUserType($my->usertype), explode(',', $config->_censorship_usertypes));;
        $this->_censorship_case_sensitive = $config->_censorship_case_sensitive;
//        $this->_censorship_words = explode(',', $config->_censorship_words);
        $this->Set_censorship_words($config->_censorship_words);
        $this->_IP_visible = $config->_IP_visible || in_array(intUserType($my->usertype), explode(',', $config->_IP_usertypes));
        $this->_IP_partial = $config->_IP_partial;
        $this->_IP_caption = $config->_IP_caption;
        $this->_IP_usertypes = explode(',', $config->_IP_usertypes);
        $this->_preview_visible = $config->_preview_visible;
        $this->_preview_length = $config->_preview_length;
        $this->_preview_lines = $config->_preview_lines;
        $this->_voting_visible = $config->_voting_visible;
        $this->_use_name = $config->_use_name;
        $this->_notify_admin = $config->_notify_admin;
        $this->_notify_email = $config->_notify_email;
        $this->_autopublish = $config->_autopublish;
        $this->_notify_users = $this->_autopublish ? $config->_notify_users : false;
        $this->_rss = $config->_rss;
        $this->_date_format = $config->_date_format;
        $this->_captcha = $config->_captcha && in_array(intUserType($my->usertype), explode(',', $config->_captcha_usertypes));
        $this->_ban = $config->_ban;
        $cb = josTableUtils::existsTable('#__comprofiler');
        $this->_profile = $config->_support_profiles && $cb;
        $this->_avatar = $config->_support_avatars && $cb;
		$this->_maxlength_text = $config->_maxlength_text;
        $this->_maxlength_word = $config->_maxlength_word;
        $this->template($this->_template);
        $this->_absolute_path = $absolutePath;
        $this->_live_site = $liveSite;
        $this->_template_path = $liveSite . '/templates/';
        $this->_emoticons_path = $liveSite . "/emoticons/$this->_emoticon_pack/images";
        $this->loadLanguage($GLOBALS['josComment_absolute_path'], $this->_language);
        $this->loadEmoticons("$absolutePath/emoticons/$this->_emoticon_pack/index.php");
        $this->_show_readon = $config->_show_readon;
        $this->_xmlerroralert = $config->_xmlerroralert ? '1' : '0';
        if ($this->_profile)        
       		$this->loadProfiles();
        $exclude = false;
    }
    
    function Set_censorship_words($censorship_words)
    {    
    	$this->_censorship_words = array();
    	
        if ($this->_censorship_enable && $censorship_words) {
            
            $censorship_words = explode(',', $censorship_words);
            
            if (is_array($censorship_words)) {
                      
            	foreach($censorship_words as $word) {
            	    
               		$word = trim($word);
               		
                	if (strpos($word, '=')) {
                    	$word = explode('=', $word);
                   		$from = trim($word[0]);
                   		$to   = trim($word[1]);  
                	} else {
                	    $from = $word;
                	    $to   = str_fill(strlen($word), '*');
                	}
                	
                	$this->_censorship_words[$from] = $to;
            	}
            }
        }
        return;
    }
    
    function jscriptInit()
    {
        global $mosConfig_live_site;
        
        $html = "\n<script type='text/javascript'>\n";
        $html .= "var JOSC_ajaxEnabled=$this->_ajax;";
        $html .= "if (!JOSC_http) JOSC_ajaxEnabled=false;";
        $html .= "var JOSC_sortDownward='$this->_sort_downward';";
        $captchaEnabled = $this->_captcha ? 'true' : 'false';
        $html .= "var JOSC_captchaEnabled=$captchaEnabled;";
        $html .= "var JOSC_liveSite='$this->_live_site';";
        $html .= "var JOSC_ConfigLiveSite='$mosConfig_live_site';";
        $html .= "var autopublish='$this->_autopublish';"; /* not used ?*/
        $html .= "var JOSC_XmlErrorAlert=$this->_xmlerroralert;";
        $html .= "\n</script>\n";
        return $html;
    }
    function loadLanguage($path, $language)
    {
        $path .= '/language/';
        if ($language == 'auto') $language = $path . $GLOBALS['mosConfig_lang'] . '.php';
        else $language = $path . $language;
        if (file_exists($language))
        	require($language);
        require($path . 'english.php');  // default is EN. non existant constants will be taken from default from this
    }
    function loadEmoticons($fileName)
    {
        require_once($fileName);
        $this->_emoticons = $GLOBALS['emoticon'];
    }
    function loadProfiles()
    {
        global $database;
        $database->setQuery('SELECT u.username, c.user_id, c.avatar 
		FROM #__users AS u, #__comprofiler AS c
		   WHERE u.id = c.user_id');
        $userList = $database->loadAssocList();
        $this->_profiles = array();
        foreach ($userList as $item) {
            /*
             * set  _profiles[userid][avatar] 
             */
            if ($this->_avatar) 
                $this->_profiles[$item['user_id']]['avatar'] = $item['avatar'];
            else  
                $this->_profiles[$item['user_id']]['avatar'] = false;

            /*
             * set  _profiles[userid][id of cb] 
             */
            if ($this->_profile) 
                $this->_profiles[$item['user_id']]['id'] = $item['user_id'];
            else 
                $this->_profiles[$item['user_id']]['id'] = false;

        }
        unset($userList);
    }
    
}

class visual extends properties {
    var $_parent_id = -1;

    function insertMenu()
    {
        $menu = new menu($this->_menu);
        $menu->setContentId($this->_contentId);
        $menu->setRSS($this->_rss);
        $menu->setModerator($this->_moderator);
        return $menu->menu_htmlCode();
    }

	function insertPoweredby()
	{
	    $html  = '<div id="poweredby" align="center" class="small">Powered by <a target="_blank" href="http://joomlacode.org/gf/project/joomagecomment/">!JoomlaComment '._JOOMLACOMMENT_CURRENT_RELEASE.'</a></div><br />';
        $html .= '<h1 style="display:none;">Copyright (C) 2007 Alain Georgette / Copyright (C) 2006 Frantisek Hliva. All rights reserved.</h1>';
	    return $html;
	}
	
    function insertSearch()
    {
        $html = $this->_search;
        $html = str_replace('{_JOOMLACOMMENT_SEARCH}', filter($this->encodeData_Charset(_JOOMLACOMMENT_SEARCH)), $html);
        $html = str_replace('{_JOOMLACOMMENT_PROMPT_KEYWORD}', filter($this->encodeData_Charset(_JOOMLACOMMENT_PROMPT_KEYWORD)), $html);
        $html = str_replace('{_JOOMLACOMMENT_SEARCH_ANYWORDS}', filter($this->encodeData_Charset(_JOOMLACOMMENT_SEARCH_ANYWORDS)), $html);
        $html = str_replace('{_JOOMLACOMMENT_SEARCH_ALLWORDS}', filter($this->encodeData_Charset(_JOOMLACOMMENT_SEARCH_ALLWORDS)), $html);
        $html = str_replace('{_JOOMLACOMMENT_SEARCH_PHRASE}', filter($this->encodeData_Charset(_JOOMLACOMMENT_SEARCH_PHRASE)), $html);
        return $html;
    }

    function insertPost($item, $postCSS, $onlyBody = false)
    {   /* post is used in module latest... ! */
        $post = new post($this->_post);
        $post->setUseName($this->_use_name); /* needed for setItem */
        $post->setItem($item);
        $post->setCSS($postCSS);
        $post->setAjax($this->_ajax);
        $post->setTree($this->_tree);
        $post->setTree_indent($this->_tree_indent);
        $post->setDate_format($this->_date_format);
        $post->setIP_visible($this->_IP_visible);
        $post->setIP_partial($this->_IP_partial);
        $post->setIP_caption($this->_IP_caption);
        $post->setIP_usertypes($this->_IP_usertypes);
        $post->setCensorShip(	$this->_censorship_enable, 
        						$this->_censorship_case_sensitive, 
        						$this->_censorship_words, 
        						$this->_censorship_usertypes 
        					);
        $post->setContentId($this->_contentId);
        $post->setVoting_visible($this->_voting_visible);
        $post->setSupport_emoticons($this->_support_emoticons);
        $post->setSupport_UBBcode($this->_support_UBBcode);
        $post->setSupport_pictures($this->_support_pictures);
        $post->setEmoticons($this->_emoticons);
        $post->setEmoticons_path($this->_emoticons_path);
        $post->setOnly_registered($this->_only_registered);
        $post->setModerator($this->_moderator);
        if ($post->_item['userid']) {
        	$post->setUser_id( $this->_profile ? $this->_profiles[$post->_item['userid']]['id'] : false );
        	$post->setAvatar( $this->_avatar ? $this->_profiles[$post->_item['userid']]['avatar'] : false );
        }
        $post->setNotify_users($this->_notify_users);
        $post->setMaxLength_text($this->_maxlength_text);
        $post->setMaxLength_word($this->_maxlength_word);
        return $post->post_htmlCode($onlyBody);
    }

    function insertComments()
    {
        global $database;
        if ($this->_sort_downward) $sort = 'DESC';
        else $sort = 'ASC';
        $database->SetQuery("SELECT * FROM #__comment WHERE contentid='$this->_contentId' AND published='1' ORDER BY id $sort");
        $data = $database->loadAssocList();
        
        $postCSS = 1;
        if ($data != null) {
            if ($this->_tree) $data = buildTree($data);
            if ($data != null) {
                $html = '';
                foreach($data as $item) {
                    $html .= $this->insertPost($item, $postCSS);
                    $postCSS++;
                    if ($postCSS == 3) $postCSS = 1;
                }
            }
        }

        return "<div id='Comments'>$html</div>\n<script type='text/javascript'>var JOSC_postCSS=$postCSS;</script>";
    }

    function insertForm()
    {
        $form = new form($this->_form);
        $form->setAbsolute_path($this->_absolute_path);
        $form->setLive_site($this->_live_site);
        $form->setOnly_registered($this->_only_registered);
        $form->setSupport_emoticons($this->_support_emoticons);
        $form->setSupport_UBBcode($this->_support_UBBcode);
        $form->setEmoticons($this->_emoticons);
        $form->setEmoticons_path($this->_emoticons_path);
        $form->setTemplate_path($this->_template_path);
        $form->setTemplate_name($this->_name);
        $form->setContentId($this->_contentId);
        $form->setCaptcha($this->_captcha);
        $form->setNotifyUsers($this->_notify_users);
        $form->setEmoticonWCount($this->_emoticon_wcount);
        $form->set_tname($this->_tname);
        $form->set_temail($this->_temail);
        $form->set_twebsite($this->_twebsite);
        $form->set_tnotify($this->_tnotify);
        return $form->form_htmlCode();
    }

    function comments($number)
    {
        if ($number == 1) $comments = _JOOMLACOMMENT_COMMENTS_1;
        elseif ($number >= 2 && $number <= 4) $comments = _JOOMLACOMMENT_COMMENTS_2_4;
        else $comments = _JOOMLACOMMENT_COMMENTS;
        return $comments;
    }

    function insertCountButton()
    {
        global $database, $Itemid;
        $adress = sefRelToAbs("index.php?option=com_content&task=view&id=$this->_contentId" . ( $Itemid ? "&Itemid=$Itemid" : "" ) );
		
        $database->SetQuery("SELECT COUNT(*) FROM #__comment WHERE contentid='$this->_contentId' AND published='1'");
        $number = $database->loadResult();
        if (!$number) $number = 0;
        $html .= "\n<div class='write_comment'>\n";
        $html .= '  <a href="';
        $html .= $adress;
        $html .= '" class="readon">' . _JOOMLACOMMENT_WRITECOMMENT . " ($number " . $this->comments($number) . ") </a>\n";
        $html .= "</div>\n";

        if ($this->_preview_visible) {
            $database->SetQuery("SELECT * FROM #__comment WHERE contentid='$this->_contentId' AND published='1' ORDER BY date DESC");
            $data = $database->loadAssocList();
            if ($data != null) {
                $html .= "\n<div class='comment_preview_container'>\n";
                $index = 0;
                foreach($data as $item) {
                    if ($index >= $this->_preview_lines) 
                    	break;
                    if ($item['title'] != '') {
                        $title = $item['title'];
                    } else { 
                    	$title = $item['comment'];    
                    }
                    if (strlen($title) > $this->_preview_length) 
                    	$title = substr($title, 0, $this->_preview_length) . '...';
					$html .= "\n<div class='comment_preview'>\n";
                    $html .= "\n	<a href=\"".$adress."#josc".$item['id']."\">" . date($this->_date_format,strtotime($item['date'])) . "&nbsp;<b>" . $title . "</b></a>\n";
					$html .= "\n</div>\n";
                    $index++;
                }
                $html .= "\n</div>\n";
            }
        }
        return $html;
    }

    function visual_htmlCode()
    {
        global $option, $task;

        $html = "";
        $html .= $this->CSS();
        $contentId = $this->decodeData_Charset('id');
        if (($option == 'com_content' && $task == 'view' && $this->_contentId == $contentId )) {

            $html .= insertJavaScript($this->_live_site);
            $this->parse();
            $html .= "<div id='comment'>";
            $html .= $this->insertMenu();
            if ($this->_sort_downward) {
                $html .= $this->insertForm();
                $html .= $this->insertComments();
                $html .= $this->insertPoweredby();
            } else {
                $html .= $this->insertComments();
                $html .= $this->insertForm();
                $html .= $this->insertPoweredby();
            }
            $html .= "</div>";
            $html .= $this->jscriptInit();
        } else
        if ($this->_show_readon) {
            $html .= $this->insertCountButton();
        } else
            nothing;

        return $html;
    }
}

class board extends visual {
    var $_contentId;
    var $_command;
    var $_userid;
    var $_usertype;
    var $_tname;
    var $_ttitle;
    var $_tcomment;
    var $_twebsite;
    var $_temail;
    var $_comment_id;
    var $_content_id;
    var $_search_keyword;
    var $_search_phrase;
    var $_charset;

    function board($absolutePath, $liveSite, $sectionId, $categoryId, &$exclude)
    {
        $this->properties($absolutePath, $liveSite, $sectionId, $categoryId, $exclude);
    }

    function setContentId($value)
    {
        $this->_contentId = $value;
    }

    function setUser() {
        global $database;
          /* also in post ! */
        $query = "SELECT * FROM #__users WHERE id='".$this->_userid."' LIMIT 1";
        $database->SetQuery($query);
        $result = $database->loadAssocList();
        if ($result) {
            $user = $result[0];
            $this->_usertype  = $user['usertype'];
            $this->_tname     = $this->_use_name ? $user['name'] : $user['username'];
            $this->_temail    = $user['email'];
        }
       
    }  

    function voting($item, $mode)
    {
        global $database;

        $t = time()-3 * 86400;
        $database->SetQuery("DELETE FROM #__comment_voting WHERE time<'$t'");
        $database->Query();
        $database->SetQuery("SELECT COUNT(*) FROM #__comment_voting WHERE id='" . $item['id'] . "' AND ip='" . $_SERVER['REMOTE_ADDR'] . "'");
        $exists = $database->loadResult();
        if (!$exists) {
            $item["voting_$mode"]++;
            $database->SetQuery("
			UPDATE #__comment SET
        	voting_$mode='" . $item["voting_$mode"] . "'
        	WHERE id=$this->_comment_id");
            $database->Query() or die('Database error: voting(1)!');
            $database->SetQuery("INSERT INTO #__comment_voting(id,ip,time)
    		VALUES(
      		'" . $item['id'] . "',
      		'" . $_SERVER['REMOTE_ADDR'] . "',
      		'" . time() . "')");
            $database->Query() or die("Database error: voting(2)!");
        }
       	$header = 'Content-Type: text/xml; charset=utf-8'; //.$this->_local_charset;
		header($header);
        $xml = '<?xml version="1.0" standalone="yes"?><voting><id>' . $item['id'] . '</id><yes>' . $item["voting_yes"] . '</yes><no>' . $item["voting_no"] . '</no></voting>';
        exit($xml);
    }

    function getNewPost($sort, &$data)
    {
        global $database;
        $database->SetQuery("SELECT * FROM #__comment WHERE contentid='$this->_contentId' AND published='1' ORDER BY id $sort");
        $data = $database->loadAssocList(); // or die('Database error: getNewPost!');
    }
    	
    function isBlocked($ip)
    {
        if ($this->_ban != '') {
            $ipList = split(',', $this->_ban);
            foreach($ipList as $item) {
                if (trim($item) == $ip) return true;
            }
        }
        return false;
    }

    function censorTextOLD($text)
    {
        if ($this->_censorship_enable && is_array($this->_censorship_words)) {
            if ($this->_censorship_case_sensitive) $replace = str_replace;
            else $replace = str_ireplace;
            foreach($this->_censorship_words as $word) {
                $word = trim($word);
                if (strpos($word, '=')) {
                    $word = explode('=', $word);
                    $text = $replace(trim($word[0]), trim($word[1]), $text);
                } else $text = $replace($word, str_fill(strlen($word), '*'), $text);
            }
        }
        return $text;
    }

    function censorText($text)
    {   /* if changed: don't forget it is also defined in post
    	 * I should factory both one day.... 
    	 */ 
        if ($this->_censorship_enable && is_array($this->_censorship_words)) {
            if ($this->_censorship_case_sensitive) $replace = str_replace;
            else $replace = str_ireplace;
            foreach($this->_censorship_words as $from => $to) {
                $text = $replace($from, $to, $text);
            }
        }
        return $text;
    }
    
    function insertNewPost($ajax = false)
    {
        $ip = $_SERVER['REMOTE_ADDR'];
        if ($this->isBlocked($ip)) return false;
        global $database, $my;
			
		$userid = $this->_userid;	
        $name = $this->censorText(mysql_escape_string(strip_tags($this->_tname)));
        $email = $this->censorText(mysql_escape_string(strip_tags($this->_temail)));
        $website = $this->censorText(mysql_escape_string(strip_tags($this->_twebsite)));
        if ( $website && strncmp( "http://", $website, 7 )!=0 )	$website = "http://" . $website;            
        $website = htmlentities($website);//ampReplace($website);
        $notify = mysql_escape_string(strip_tags($this->_tnotify)) ? true : false ;
        $title = $this->censorText(mysql_escape_string(strip_tags($this->_ttitle)));
        $comment = $this->censorText(mysql_escape_string(strip_tags($this->_tcomment)));
        $published = $this->_autopublish;
        $parent_id = $this->_parent_id;
        $database->SetQuery("
            INSERT INTO #__comment
            (contentid,ip,userid,usertype,date,name,email,website,notify,title,comment,published,voting_yes,voting_no,parentid)
            VALUES(
            '$this->_content_id',
            '$ip',
            '$userid',
            '$usertype',
            now(),
            '$name',
            '$email',
            '$website',
            '$notify',
            '$title',
            '$comment',
            '$published',
            '0',
            '0',
            '$parent_id'
            )");
        $result=$database->Query() or die(_JOOMLACOMMENT_SAVINGFAILED);
        
        $this->_comment_id = $database->insertid();
		
        $lists = array();
        $lists['commentid'] = $this->_comment_id;
        $lists['contentid'] = $this->_content_id;
        $lists['name'] 		= $name;
        $lists['title'] 	= $title;
        $lists['notify'] 	= $notify;
        $lists['comment']	= $comment;
                
        $lists['email'] 	= $this->_notify_email;
        if ($this->_notify_admin) notifyAdmin( $lists );
        $lists['email'] 	= $email;
        if ($this->_notify_users) notifyUsers( $lists );

        if ($ajax) {
            if ($this->_tree) {
                $this->getNewPost('ASC', $data); /* get all post of the content_id */
                if ($data) {
                $id = $data[sizeOf($data)-1]['id'];
                $data = buildTree($data);
                $after = -1;
                foreach($data as $item) {
                    if ($item['id'] == $id) {
                        $item['after'] = $after;
                        $item['view'] = $published;
                        $item['noerror'] = 1;
                        return $item;
                    }
                    $after = $item['id'];
                }
                }
            } else $this->getNewPost('DESC LIMIT 1', $data);
            $data[0]['view'] = $published;
            $data[0]['noerror'] = 1;
            return $data[0];
        } else return $published;
    }

    function editPost()
    {
	    $ip = $_SERVER['REMOTE_ADDR'];
        if ($this->isBlocked($ip)) return false;
                
        global $database;

       	$database->SetQuery("SELECT * FROM #__comment WHERE id='$this->_comment_id'");
       	$item = $database->loadAssocList();
		    
		if ($this->checkEditPost($item[0])) {            
           	$title = $this->censorText(mysql_escape_string(strip_tags($this->_ttitle)));
           	$comment = $this->censorText(mysql_escape_string(strip_tags($this->_tcomment)));
	       	$website = $this->censorText(mysql_escape_string(strip_tags($this->_twebsite)));
     	  		if ( $website && strncmp( "http://", $website, 7 )!=0 )	$website = "http://" . $website;            
        	$website = htmlentities($website);//ampReplace($website);
        	$notify = mysql_escape_string(strip_tags($this->_tnotify)) ? '1' : '0' ;
        	$query = "
           	UPDATE #__comment SET
           		date=now()
           		,title='$title'
           		,comment='$comment'
          		 	,website='$website'
           		,notify='$notify'
           	WHERE id=$this->_comment_id";
           	$database->SetQuery($query);
           	$database->Query() or die(_JOOMLACOMMENT_EDITINGFAILED . "\n $query");
           	$database->SetQuery("SELECT * FROM #__comment WHERE id='$this->_comment_id' AND published='1' LIMIT 1");
           	$data = $database->loadAssocList() or die('Database error: editPost!');
           	$data[0]['view'] = 1;
           	$data[0]['noerror'] = 1;
           	return $data[0];
        }
    }

	function checkEditPost($item) 
	{
		global $my;
		
        if ( ($my->id && $my->id==$item['userid'] ) || isCommentModerator($this->_moderator, $item['name'], $item['usertype']))
          return true;
        else
          return false;    
	}    
	
    function modify($event = false)
    {
 		/* example of call : $this->modify(editPost) 
 		 * 	  	event is a method which will be called below as  $this->$event(true)
 		 * 		where true means ajax call.
 		 */   	
        global $my;
        if (!$event) {
            if (!$my->username && $this->_only_registered)
                showMessage(_JOOMLACOMMENT_ONLYREGISTERED);
            else if (!($this->_captcha && !captchaResult())) {
                $published = $this->insertNewPost();
                unset($this->_tcomment);
                mosCache::cleanCache( 'com_content' );
                mosRedirect(sefRelToAbs("index.php?option=com_content&task=view&id=$this->_content_id".($this->_comment_id ? "#josc$this->_comment_id" : "")), $published ? '':_JOOMLACOMMENT_BEFORE_APPROVAL);
            }
            mosRedirect(sefRelToAbs("index.php?option=com_content&task=view&id=$this->_content_id"));
        }
       	$header = 'Content-Type: text/xml; charset=utf-8'; //.$this->_local_charset;
       	header($header);
        if (!($this->_captcha && !captchaResult())) {
            $this->setContentId($this->_content_id);
            $item = $this->$event(true);
            if (!$item) exit();
            $this->parse();
            $xml = '<?xml version="1.0" standalone="yes"?>';
            $xml .= '<post>';
            $xml .= '<id>' . $item['id'] . '</id>';
            if ($this->_tree) $xml .= '<after>' . $item['after'] . '</after>';
            $html = cdata(filter($this->encodeData_Charset($this->insertPost($item, ''))));
            $xml .= "<body>$html</body>";
            if ($this->_captcha) {
                $captcha = cdata(insertCaptcha('security_refid'));
                $xml .= "<captcha>$captcha</captcha>";
            }
            $xml .= '<published>' . $item['view'] . '</published>';
            $xml .= '<noerror>' . $item['noerror'] . '</noerror>';
            $xml .= '</post>';
			mosCache::cleanCache( 'com_content' );           
            exit($xml);
        } else if ($this->_captcha) {
            $captcha = cdata(insertCaptcha('security_refid'));
            $xml = '<?xml version="1.0" standalone="yes"?>';
            $xml .= '<post>';
            $xml .= '<id>captcha</id>'; /* will alert  */
            $xml .= "<captcha>$captcha</captcha>";
            $xml .= '<noerror>1</noerror>';
            $xml .= '</post>';
            
            exit($xml);
        } else exit;
    }

    function deletePost($id = -1)
    {
        global $database;
        $id = ($id == -1) ? "WHERE contentid='$this->_content_id'" : "WHERE id='$id'";
        $database->SetQuery("DELETE FROM #__comment $id");
        $database->Query() or die(_JOOMLACOMMENT_DELETINGFAILED);
    }

    function search()
    {
        $this->parse();
        $search = new search($this->_searchResults);
        $search->setKeyword($this->_search_keyword);
        $search->setPhrase($this->_search_phrase);
        $search->setDate_format($this->_date_format);
        $search->setAjax($this->_ajax);
        $search->setLocalCharset($this->_local_charset);
        return $search->search_htmlCode();
    }

    function filterAll($item)
    {
        $item['name'] 	= filter($this->encodeData_Charset($item['name']));
        $item['title'] 	= filter($this->encodeData_Charset($item['title']));
        $item['comment'] = filter($this->encodeData_Charset($item['comment']));
/*        $item['name'] 	= filter($item['name']);
        $item['title'] 	= filter($item['title']);
        $item['comment'] = filter($item['comment']);*/
        return $item;
    }

    function decodeURI()
    {
        global $my;
        
        $this->_command = $this->decodeData_Charset('command');

        if ($my->username) {
	        $this->_userid = $my->id;
            $this->_usertype = $my->usertype;
            $this->_tname = $my->username;
            $this->setUser();
        } else {
	        $this->_userid = 0;
        	$this->_usertype = 'Unregistered';   
	        $this->_tname = $this->decodeData_Charset('tname');
    	    $this->_temail = $this->decodeData_Charset('temail');
        }
        
        $this->_tnotify = $this->decodeData_Charset('tnotify');
        $this->_twebsite = $this->decodeData_Charset('twebsite');
        $this->_ttitle = $this->decodeData_Charset('ttitle');
        $this->_tcomment = $this->decodeData_Charset('tcomment');
        $this->_comment_id = $this->decodeData_Charset('comment_id');
        $this->_content_id = $this->decodeData_Charset('content_id');
        $this->_search_keyword = $this->decodeData_Charset('search_keyword');
        $this->_search_phrase = $this->decodeData_Charset('search_phrase');
        $this->_parent_id = $this->decodeData_Charset('parent_id');
        if ($this->_parent_id == '') $this->_parent_id = '-1';
    }

    function decodeData_Charset($varName) {
	/*  ALSO IN SEARCH CLASS
	 * javascript(ajax) encodeURI is only UTF-8. so we have to decode ajax send
	 * should be solved with joomla 1.5 ! (native utf-8)
	 */
	 if ($this->_ajax)
        return myiconv_decode( decodeData($varName), $this->_local_charset );
     else
     	return decodeData($varName);    	
    }
    
    function encodeData_Charset($var) {
	/*  ALSO IN SEARCH CLASS
	 *  javascript(ajax) encodeURI is only UTF-8. so we have to decode ajax send
	 * should be solved with joomla 1.5 ! (native utf-8)
	 */
	 if ($this->_ajax)
        return myiconv_encode( $var , $this->_local_charset );
     else
     	return $var;  	        
    }
       
    function execute()
    {
        global $database;
        $this->decodeURI();
        /* don't forget that ajax_code are first checked in comment.php ! */
        if ($this->_command) {
            $query = "SELECT * FROM #__comment WHERE id='$this->_comment_id' LIMIT 1";
            $database->SetQuery($query);
            $item = $database->loadAssocList();
            $itemsave = $item[0];
            if ($this->checkEditPost($itemsave)) {
                if ($this->_command == 'ajax_delete') {
                    $this->deletePost($this->_comment_id);
                    exit;
                }
                if ($this->_command == 'ajax_delete_all') {
                    $this->deletePost();
                    exit;
                }
                if ($this->_command == 'ajax_edit') $this->modify(editPost);
            }
            if ($this->_command == 'ajax_insert') $this->modify(insertNewPost);
            if ($this->_command == 'ajax_modify' || $this->_command == 'ajax_quote') {
                $item = $this->filterAll($item[0]);
     	       	$header = 'Content-Type: text/xml; charset=utf-8'; //.$this->_local_charset; not ok for IE ! only utf-8 is possible
       			header($header);
                $item['email'] = ($item['userid'] ? _JOOMLACOMMENT_AUTOMATICEMAIL : $item['email']);
                $xml = '<?xml version="1.0" standalone="yes"?><post>'
                	 . '<name>'     . cdata($item['name'])    .'</name>'
                	 . '<title>'    . cdata($item['title'])   . '</title>'
					 . '<comment>'  . cdata($item['comment']) . '</comment>'
					 ;
					 if ($this->_command == 'ajax_modify' && $this->checkEditPost($itemsave)) {
					 $xml 	.= '<email>'    . cdata($item['email'])   . '</email>'
//					 		. '<userid>'   . cdata($item['userid'])  . '</userid>'
					 		. '<notify>'   . cdata($item['notify'])  . '</notify>'
					 		. '<website>'  . cdata($item['website']) . '</website>'
					 ;
					 }
					 
				$xml .= '</post>'
					 ;
                exit($xml);
            }
            if ($this->_command == 'ajax_voting_yes') $this->voting($item[0], 'yes');
            if ($this->_command == 'ajax_voting_no') $this->voting($item[0], 'no');
            if ($this->_command == 'ajax_insert_search') {
                $this->parse();
     	       	$header = 'Content-Type: text/xml; charset=utf-8'; //.$this->_local_charset;
       			header($header);
                exit($this->insertSearch());
            }
            if ($this->_command == 'ajax_search') {
     	       	$header = 'Content-Type: text/xml; charset=utf-8'; //charset='.$this->_local_charset;
       			header($header);
                exit($this->search());
            }
        } else if ($this->_tcomment) $this->modify(false);
    }
}

class tree {
    var $_id;
    var $_counter;

    function getSeed($data, $seed)
    {
        $this->_counter++;
        if ($seed) {
            foreach($seed as $item) {
                $data[$item]['wrapnum'] = $this->_counter;
                $this->_new[] = $data[$item];
                if ($data[$item]['seed']) {
                    $this->getSeed($data, $data[$item]['seed']);
                    $data[$item] = null;
                }
            }
        }
        $this->_counter--;
    }

    function build($data)
    {
        $index = 0;
        $this->_new = null;
        $this->_counter = 0;

        foreach($data as $item) {
            $old[$item['id']] = $index;
            $data[$index]['treeid'] = $index;
            if ($data[$index]['parentid'] != -1) $data[$index]['parentid'] = $old[$item['parentid']];
            $index++;
        }

        foreach($data as $item)
        	if ($item['parentid'] != -1) $data[$item['parentid']]['seed'][] = $item['treeid'];

        foreach($data as $item) {
            if ($item['parentid'] == -1) {
                $this->_new[] = $item;
                if ($item['seed']) $this->getSeed($data, $item['seed']);
            }
        }
        return $this->_new;
    }
}


class support {
    var $_ajax;
    var $_local_charset;
    var $_absolute_path;
    var $_live_site;
    var $_only_registered;
    var $_support_emoticons;
    var $_support_UBBcode;
    var $_support_pictures;
    var $_hide;
    var $_emoticons;
    var $_emoticons_path;
    var $_contentId;
    var $_moderator;
    var $_show_readon;
    var $_date_format;

    function setAjax($value)
    {
        $this->_ajax = $value;
    }

    function setLocalCharset($value)
    {
        $this->_local_charset = $value;
    }

    function setAbsolute_path($value)
    {
        $this->_absolute_path = $value;
    }

    function setLive_site($value)
    {
        $this->_live_site = $value;
    }

    function setOnly_registered($value)
    {
        $this->_only_registered = $value;
    }

    function setSupport_emoticons($value)
    {
        $this->_support_emoticons = $value;
    }

    function setSupport_UBBcode($value)
    {
        $this->_support_UBBcode = $value;
    }

    function setSupport_pictures($value)
    {
        $this->_support_pictures = $value;
    }

    function setHide($value)
    {
        $this->_hide = $value;
    }

    function setEmoticons($value)
    {
        $this->_emoticons = $value;
    }

    function setEmoticons_path($value)
    {
        $this->_emoticons_path = $value;
    }

	function setContentId($value)
    {
        $this->_contentId = $value;
    }

	function setModerator($value)
    {
        $this->_moderator = $value;
    }
    
    function setReadon($value)
    {
        $this->_show_readon= $value;
    }
    
    function setDate_format($value)
    {
        $this->_date_format = $value;
    }
}


class menu extends support {
    var $_menu;
    var $_rss;

    function menu($value)
    {
        $this->_menu = $value;
    }

    function setRSS($value)
    {
        $this->_rss = $value;
    }

    function insertButton($text, $link, $icon = '')
    {
        if ($icon) $icon = "<img class='menuicon' src='$icon' alt='$icon' />";
        return "<td class='button'><a id='$text' href='$link'>$icon$text</a></td>";
    }

    function menu_htmlCode()
    {
        $buttons .= $this->insertButton(_JOOMLACOMMENT_ADDNEW, 'javascript:JOSC_addNew()');
        if (isCommentModerator($this->_moderator)) $buttons .= $this->insertButton(_JOOMLACOMMENT_DELETEALL, 'javascript:JOSC_deleteAll()');
        $buttons .= $this->insertButton(_JOOMLACOMMENT_SEARCH, 'javascript:JOSC_searchForm()');
        if ($this->_rss) $buttons .= $this->insertButton(_JOOMLACOMMENT_RSS, "index2.php?option=com_comment&no_html=1&command=rss&contentid=$this->_contentId");
        $html = str_replace('{_COMMENTS_2_4}', _JOOMLACOMMENT_COMMENTS_2_4, $this->_menu);
        $html = str_replace('{buttons}', $buttons, $html);
        return $html;
    }
}


class post extends support {
    var $_post;
    var $_item;
    var $_css;
    var $_tree;
    var $_tree_indent;
    var $_IP_visible;
    var $_IP_partial;
    var $_IP_caption;
    var $_IP_usertypes;
    var $_censorship_enable;
    var $_censorship_case_sensitive;
    var $_censorship_words;
    var $_censorship_usertypes;    
    var $_voting_visible;
    var $_avatar;
    var $_user_id;
    var $_use_name;
    var $_notify_users;
    var $_maxlength_text;
    var $_maxlength_word;

    function post($value)
    {
        $this->_post = $value;
    }

	/*
	 * AGE comment: the use of the following methods to just set the value seems heavy 
	 * but this is a professional way to code from joomlacomment developpers
	 */
    function setItem($value)
    {
        $this->_item = $value;
        $this->setUser(); /* _use_name has to be set ! refresh comment user values according to */
        
    }
    
    function setUser() {
        global $database;
        
        if (!$this->_item || !$this->_item['userid'])
        	return;
			     
        $query = "SELECT * FROM #__users WHERE id='".$this->_item['userid']."' LIMIT 1";
        $database->SetQuery($query);
        $result = $database->loadAssocList();
        if ($result) {
            $user = $result[0];
            $this->_item['name']     = $this->_use_name ? $user['name'] : $user['username'];
            $this->_item['usertype'] = $user['usertype'];
            $this->_item['email']    = $user['email'];
        }
       
    }  

    function setCSS($value)
    {
        $this->_css = $value;
    }

    function setTree($value)
    {
        $this->_tree = $value;
    }

    function setTree_indent($value)
    {
        $this->_tree_indent = $value;
    }

    function setIP_visible($value)
    {
        $this->_IP_visible = $value;
    }

    function setIP_partial($value)
    {
        $this->_IP_partial = $value;
    }

    function setIP_caption($value)
    {
        $this->_IP_caption = $value;
    }

    function setIP_usertypes($value)
    {
        $this->_IP_usertypes = $value;
    }

	function setCensorShip($enable, $case_sensitive, $words, $usertypes ) {
    	$this->_censorship_enable 			= $enable;
    	$this->_censorship_case_sensitive 	= $case_sensitive;
    	$this->_censorship_words 			= $words;
    	$this->_censorship_usertypes 		= $usertypes; 
	}
	
    function setVoting_visible($value)
    {
        $this->_voting_visible = $value;
    }

    function setAvatar($value)
    {
        $this->_avatar = $value;
    }

    function setUseName($value)
    {
        $this->_use_name = $value;
    }

    function setUser_id($value)
    {
        $this->_user_id = $value;
    }

    function setNotify_users($value)
    {
        $this->_notify_users = $value;
    }

    function setMaxlength_text($value)
    {
        $this->_maxlength_text = $value;
    }

    function setMaxlength_word($value)
    {
        $this->_maxlength_word = $value;
    }

    function censorText($text)
    {   /* if changed: don't forget it is also defined in board
    	 * I should factory both one day.... 
    	 */ 
        if ($this->_censorship_enable && is_array($this->_censorship_words)) {
            if ($this->_censorship_case_sensitive) $replace = str_replace;
            else $replace = str_ireplace;
            foreach($this->_censorship_words as $from => $to) {
                $text = $replace($from, $to, $text);
            }
        }
        return $text;
    }
    
    function highlightAdmin($usertype)
    {
        if (strpos($usertype, 'Administrator'))
            $usertype = "<span class='administrator'>$usertype</span>";
        return $usertype;
    }

    function anonymous($name)
    {
        if ($name == '') $name = _JOOMLACOMMENT_ANONYMOUS;
        return $name;
    }

    function space($title)
    {
        if ($title == '') return '';
        return ' - ';
    }

    function IP($ip, $usertype, $visible, $partial, $caption)
    {
        if (in_array(intUserType($usertype), $this->_IP_usertypes) && $visible) {
            if ($partial) $ip = partialIP($ip);
            return $caption . $ip;
        } else return $this->highlightAdmin($usertype);
    }

    function linkQuote($id)
    {
        return "<a href = 'javascript:JOSC_quote($id)'>" . _JOOMLACOMMENT_QUOTE . "</a>";
    }

    function linkPost($id)
    {
        return "<a href='javascript:JOSC_reply($id)'>" . _JOOMLACOMMENT_REPLY . '</a>';
    }

    function linkEdit($id)
    {
        return "<a href='javascript:JOSC_editComment($id)'>" . _JOOMLACOMMENT_EDIT . '</a>';
    }

    function linkDelete($id)
    {
        return "<a href='javascript:JOSC_deleteComment($id)'>" . _JOOMLACOMMENT_DELETE . '</a>';
    }

    function voting_cell($mode, $num, $id)
    {
        return "<td><a id='$mode$id' class='voting_$mode' href='javascript:JOSC_voting($id,\"$mode\")'>$num</a></td>";
    }

    function voting($voting_no, $voting_yes, $id, $contentId)
    {
        $html = '';
        if ($this->_voting_visible) {
            if ($voting_yes == '') {
                $voting_yes = 0;
                $voting_no = 0;
            }
            $html .= "<table cellspacing='0' cellpadding='0' border='0'>";
            $html .= "<tr>" . $this->voting_cell('yes', $voting_yes, $id);
            $html .= "<td>&nbsp;</td>";
            $html .= $this->voting_cell('no', $voting_no, $id) . "</tr>";
            $html .= "</table>";
        }
		/*
		 * If voting no are 2x greater than voting yes => mode hide
		 */
        $this->_hide = (($voting_no + 1) > (($voting_yes + 1) * 2)); 
        return $html;
    }

    function parseUBBCode($html)
    {
        $ubbcode = new ubbcode($html);
        $ubbcode->setSupport_emoticons($this->_support_emoticons);
        $ubbcode->setSupport_UBBcode($this->_support_UBBcode);
        $ubbcode->setSupport_pictures($this->_support_pictures);
        $ubbcode->setHide($this->_hide);
        $ubbcode->setEmoticons($this->_emoticons);
        $ubbcode->setEmoticons_path($this->_emoticons_path);
        return $ubbcode->ubbcode_parse();
    }

    function envelope($html, $id, $wrapnum)
    {
        $wrapnum = ($this->_tree) ? $wrapnum : 0;
        $result = "<table class='postcontainer' id='post$id' width='100%' cellpadding='0' cellspacing='0' style='padding-left: $wrapnum;'>";
        $result .= "<tr><td><a name='josc$id'></a>$html</td></tr>";
        $result .= "</table>";
        return $result;
    }

    function setMaxLength($text)
    {
        if ($this->_maxlength_word != -1) $text = wrapText($text, $this->_maxlength_word);
        if (($this->_maxlength_text != -1) && (strlen($text) > $this->_maxlength_text))
            $text = substr($text, 0, $this->_maxlength_text) . '...';
        return $text;
    }

    function profileLink($s, $id)
    {
        global $mosConfig_live_site;
        return $id ? "<a href='$mosConfig_live_site/index.php?option=com_comprofiler&task=userProfile&user=$id'>$s</a>" : $s;
    }

    function post_htmlCode()
    {
        global $my, $gid, $mosConfig_live_site;

		/*
		 * use ' character instead of \" in html code
		 */        

        $id 		= $this->_item['id'];
        $name	 	= $this->censorText(filter($this->anonymous($this->_item['name'])));
        $website 	= $this->censorText(filter($this->_item['website']));
        $notify 	= $this->_item['notify'];
//        $email =  $gid > 1 ? $this->_item['email'] : ""; /* admin -> show email */
        $notify 	= $this->_item['notify'];
        $title 		= $this->censorText(filter($this->_item['title']));
        $comment 	= $this->censorText(filter($this->_item['comment']));
        $usertype 	= $this->_item['usertype'];
        $ip 		= $this->_item['ip'];
        $date 		= date($this->_date_format, strToTime($this->_item['date']));
        $edit 		= '';
        if ($this->_tree) $edit = $this->linkPost($id);
        if ($this->_support_UBBcode) {
            if ($edit) $edit .= ' | ';
            $edit .= $this->linkQuote($id);
        }
        if ($my->username && isCommentModerator($this->_moderator, $name, $usertype)) {
            if ($edit) $edit .= ' | ';
            $edit .= $this->linkEdit($id);
            $edit .= ' | ' . $this->linkDelete($id);
        }
        $voting 	= $this->voting($this->_item['voting_no'], $this->_item['voting_yes'], $id, $this->_contentId);
        $comment 	= $this->setMaxLength($comment); /* before emoticons tags ! */
        $comment 	= $this->parseUBBCode($comment);
        $html 		= $this->_post;
        $html 		= ignoreBlock($html, 'footer', ((!$my->username && $this->_only_registered) || !$this->_ajax || ($edit == '')));
        $html 		= ignoreBlock($html, 'avatar', !$this->_avatar);
        if ($this->_avatar) {
			if(strpos($this->_avatar,"gallery/")===false) 
	            $path = "$mosConfig_live_site/images/comprofiler/tn$this->_avatar";
			else
	            $path = "$mosConfig_live_site/images/comprofiler/$this->_avatar";		            
            $html = str_replace('{avatar_picture}', $this->profileLink("<img class='avatar' src='$path' alt='avatar' />", $this->_user_id), $html);
        }
        $html 		= str_replace('{postclass}', 'sectiontableentry' . $this->_css, $html);
        $html 		= str_replace('{username}', $this->profileLink($name, $this->_user_id), $html);
        	
        if ($website)  	$website = "<a class='postwebsite' href='$website' title='$website' target='_blank'>&nbsp;</a>";
        $html 		= str_replace('{spacewww}', $this->space($website), $html);
        $html 		= str_replace('{website}', $website, $html);
        $notifyactive = ($this->_notify_users && $notify) ? '1' : '0';
		$notify 		= "<span class='postnotify$notifyactive' title='".( $notifyactive ? ( _JOOMLACOMMENT_NOTIFYTXT1 ) : _JOOMLACOMMENT_NOTIFYTXT0 )."'>&nbsp;</span>";
        $html 		= str_replace('{notify}', $notify , $html);
        $html 		= str_replace('{space}', $this->space($title), $html);
        $html 		= str_replace('{title}', $title, $html);
        $html 		= str_replace('{usertype}', $this->IP($ip, $usertype, $this->_IP_visible, $this->_IP_partial, $this->_IP_caption), $html);
        $html 		= str_replace('{date}', $date, $html);
        $html 		= str_replace('{content}', $comment, $html);
        $html 		= str_replace('{editbuttons}', $edit, $html);
        $html 		= str_replace('{voting}', $voting, $html);
        return $this->envelope($html, $id, ($this->_item['wrapnum'] * $this->_tree_indent) . 'px');
    }
}


class ubbcode extends support {
    var $_comment;

    function ubbcode($value)
    {
        $this->_comment = $value;
    }

    function parseEmoticons($html)
    {
        foreach ($this->_emoticons as $ubb => $icon) {
            $html = str_replace($ubb, "<img src='" . $this->_emoticons_path . '/' . $icon . "' border='0' alt='$i' />", $html);
        }
        return $html;
    }

    function parseImgElement($html)
    {
        return preg_replace('/\[img\](.*?)\[\/img\]/i', '<img src=\'\\1\' alt=\'Posted image\' />', $html);
    }

    function parseQuoteElement($html)
    {
        $q1 = substr_count($html, "[/quote]");
        $q2 = substr_count($html, "[quote=");
        if ($q1 > $q2) $quotes = $q1;
        else $quotes = $q2;
        $patterns = array("/\[quote\](.+?)\[\/quote\]/is",
            "/\[quote=(.+?)\](.+?)\[\/quote\]/is");
        $replacements = array("<div class='quote'><div class='genmed'><b>" . _JOOMLACOMMENT_UBB_QUOTE . "</b></div><div class='quotebody'>\\1</div></div>",
            "<div class='quote'><div class='genmed'><b>\\1 " . _JOOMLACOMMENT_UBB_WROTE . "</b></div><div class='quotebody'>\\2</div></div>");
        while ($quotes > 0) {
            $html = preg_replace($patterns, $replacements, $html);
            $quotes--;
        }
        return $html;
    }

    function code_unprotect($val)
    {
        $val = str_replace("{ : }", ":", $val);
        $val = str_replace("{ ; }", ";", $val);
        $val = str_replace("{ [ }", "[", $val);
        $val = str_replace("{ ] }", "]", $val);
        $val = str_replace(array("\n\r", "\r\n"), "\r", $val);
        $val = str_replace("\r", '&#13;', $val);
		return filter($val, true);
    }

    function parseCodeElement($html)
    {
		if (preg_match_all('/\[code\](.+?)\[\/code\]/is', $html, $replacementI)) {
			foreach($replacementI[0] as $val) $html = str_replace($val, $this->code_unprotect($val), $html);
        }
        $pattern = array();
        $replacement = array();
        $pattern[] = "/\[code\](.+?)\[\/code\]/is";
        $replacement[] = "<div class='code'><div class='genmed'><b>" . _JOOMLACOMMENT_UBB_CODE . '</b></div><pre>\\1</pre></div>';
        return preg_replace($pattern, $replacement, $html);
    }

    function parseUBB($html, $hide)
    {
        $html = str_replace(']www.', ']http://www.', $html);
        $html = str_replace('=www.', '=http://www.', $html);
        $patterns = array('/\[b\](.*?)\[\/b\]/i',
            '/\[u\](.*?)\[\/u\]/i',
            '/\[i\](.*?)\[\/i\]/i',
            '/\[url=(.*?)\](.*?)\[\/url\]/i',
            '/\[url\](.*?)\[\/url\]/i',
            '#\[email\]([a-z0-9\-_.]+?@[\w\-]+\.([\w\-\.]+\.)?[\w]+)\[/email\]#',
            '#\[email=([a-z0-9\-_.]+?@[\w\-]+\.([\w\-\.]+\.)?[\w]+)\](.*?)\[/email\]#',
            '/\[font=(.*?)\](.*?)\[\/font\]/i',
            '/\[size=(.*?)\](.*?)\[\/size\]/i',
            '/\[color=(.*?)\](.*?)\[\/color\]/i');
        $replacements = array('<b>\\1</b>',
            '<u>\\1</u>',
            '<i>\\1</i>',
            '<a href=\'\\1\' title=\'Visit \\1\'>\\2</a>',
            '<a href=\'\\1\' title=\'Visit \\1\'>\\1</a>',
            '<a href=\'mailto:\\1\'>\\1</a>',
            '<a href=\'mailto:\\1\'>\\3</a>',
            '<span style=\'font-family: \\1\'>\\2</span>',
            '<span style=\'font-size: \\1\'>\\2</span>');
        if ($hide) $replacements[] = '\\2';
        else $replacements[] = '<span style=\'color: \\1\'>\\2</span>';
        $html = preg_replace($patterns, $replacements, $html);
        return $html;
    }

    function ubbcode_parse()
    {
        global $mosConfig_absolute_path;

		$html = $this->_comment;
        if ($this->_support_emoticons) $html = $this->parseEmoticons($html);
        if ($this->_support_pictures) $html = $this->parseImgElement($html);
        if ($this->_support_UBBcode) {
            $html = $this->parseUBB($html, $this->_hide);
            $html = $this->parseCodeElement($html);
            $html = $this->parseQuoteElement($html);
        }
        if ($this->_hide) $html = "<span class='hide'>$html</span>";
		return str_replace('&#13;', "\r", nl2br($html));
    }
}


class form extends support {
    var $_form;
    var $_template_path;
    var $_template_name;
    var $_captcha;
    var $_notify_users;
    var $_emoticon_wcount;
    var $_tname;
    var $_temail;
    var $_twebsite;
    var $_tnotify;

    function form($value)
    {
        $this->_form = $value;
    }

    function setTemplate_path($value)
    {
        $this->_template_path = $value;
    }

    function setTemplate_name($value)
    {
        $this->_template_name = $value;
    }

    function setCaptcha($value)
    {
        $this->_captcha = $value;
    }

    function setNotifyUsers($value)
    {
        $this->_notify_users = $value;
    }

    function setEmoticonWCount($value)
    {
        $this->_emoticon_wcount = $value;
    }

    function set_tname($value)
    {
        $this->_tname = $value;
    }

    function set_temail($value)
    {
        global $my;
        
        $this->_temail = ($my->id ? _JOOMLACOMMENT_AUTOMATICEMAIL : $value); /* change also modify - ajax_quote ! */
    }

    function set_twebsite($value)
    {
        $this->_twebsite = $value;
    }

    function set_tnotify($value)
    {
        $this->_tnotify = $value;
    }

    function onlyRegistered()
    {
        return '<div class="onlyregistered">' . _JOOMLACOMMENT_ONLYREGISTERED . '</div>';
    }

    function readOnly($username)
    {
        if ($username) return 'DISABLED';
        else return '';
    }

    function displayStyle($display)
    {
        return ($display) ? "" : "display:none;";
    }

    function emoticons($link=true)
    {
        if (!$this->_support_emoticons) return '';
        $html = "<div class='emoticoncontainer'>";
        $html .= "<div class='emoticonseparator'></div>";
        $index = 0;
        $icon_used = array();
        foreach ($GLOBALS["emoticon"] as $ubb => $icon) {

            if (in_array($icon, $icon_used))
                continue;  /* ignore: avoid same icons twice ! */

            $icon_used[] = $icon;

            $html .= "<span class='emoticonseparator'>";
            $html .= "<span class='emoticon'>";
            $html .= $link ? "<a href='javascript:JOSC_emoticon(\"$ubb\")'>" : "";
            $html .= "<img src='$this->_emoticons_path/$icon' border='0' alt='$i' />";
            $html .= $link ? "</a>":"";
            $html .= "</span></span>";
            $index++;
            if ($index == $this->_emoticon_wcount) {
                $index = 0;
                $html .= "<div class='emoticonseparator'></div>";
            }
        }
        $html .= '</div>';
        return "<div>$html</div>";
    }

    function loadUBBIcons(&$ubbIconList, $absolute_path, $live_site)
    {
        require_once("$absolute_path/ubb_icons.php");
        foreach($ubbIcons as $name => $icon) {
            $ubbIconList[$name] = "$live_site/$icon";
        }
    }

    function UBBCodeButtons()
    {
        $absolute_path = "$this->_absolute_path/templates/$this->_template_name/images";
        $live_site = "$this->_template_path/$this->_template_name/images";
        $ubbIconList = array();
        $this->loadUBBIcons($ubbIconList, "$this->_absolute_path/images", "$this->_live_site/images");
        if (file_exists("$absolute_path/ubb_icons.php")) $this->loadUBBIcons($ubbIconList, $absolute_path, $live_site);
        $html = "<a href='javascript:JOSC_insertUBBTag(\"b\")'><img src='" . $ubbIconList['bold'] . "' class='buttonBB' name='bb' alt='[b]' /></a>&nbsp;";
        $html .= "<a href='javascript:JOSC_insertUBBTag(\"i\")'><img src='" . $ubbIconList['italicize'] . "' class='buttonBB' name='bi' alt='[i]' /></a>&nbsp;";
        $html .= "<a href='javascript:JOSC_insertUBBTag(\"u\")'><img src='" . $ubbIconList['underline'] . "' class='buttonBB' name='bu' alt='[u]' /></a>&nbsp;";
        $html .= "<a href='javascript:JOSC_insertUBBTag(\"url\")'><img src='" . $ubbIconList['url'] . "' class='buttonBB' name='burl' alt='[url]' /></a>&nbsp;";
        $html .= "<a href='javascript:JOSC_insertUBBTag(\"quote\")'><img src='" . $ubbIconList['quote'] . "' class='buttonBB' name='bquote' alt='[quote]' /></a>&nbsp;";
        $html .= "<a href='javascript:JOSC_insertUBBTag(\"code\")'><img src='" . $ubbIconList['code'] . "' class='buttonBB' name='bcode' alt='[code]' /></a>&nbsp;";
        $html .= "<a href='javascript:JOSC_insertUBBTag(\"img\")'><img src='" . $ubbIconList['image'] . "' class='buttonBB' name='bimg' alt='[img]' /></a>&nbsp;";
        return $html;
    }

    function UBBCodeSelect()
    {
        $html = '';
        $html .= "<select name='menuColor' class='select' onchange='JOSC_fontColor()'>";
        $html .= "<option>-" . _JOOMLACOMMENT_COLOR . "-</option>";
        $html .= "<option>" . _JOOMLACOMMENT_AQUA . "</option>";
        $html .= "<option>" . _JOOMLACOMMENT_BLACK . "</option>";
        $html .= "<option>" . _JOOMLACOMMENT_BLUE . "</option>";
        $html .= "<option>" . _JOOMLACOMMENT_FUCHSIA . "</option>";
        $html .= "<option>" . _JOOMLACOMMENT_GRAY . "</option>";
        $html .= "<option>" . _JOOMLACOMMENT_GREEN . "</option>";
        $html .= "<option>" . _JOOMLACOMMENT_LIME . "</option>";
        $html .= "<option>" . _JOOMLACOMMENT_MAROON . "</option>";
        $html .= "<option>" . _JOOMLACOMMENT_NAVY . "</option>";
        $html .= "<option>" . _JOOMLACOMMENT_OLIVE . "</option>";
        $html .= "<option>" . _JOOMLACOMMENT_PURPLE . "</option>";
        $html .= "<option>" . _JOOMLACOMMENT_RED . "</option>";
        $html .= "<option>" . _JOOMLACOMMENT_SILVER . "</option>";
        $html .= "<option>" . _JOOMLACOMMENT_TEAL . "</option>";
        $html .= "<option>" . _JOOMLACOMMENT_WHITE . "</option>";
        $html .= "<option>" . _JOOMLACOMMENT_YELLOW . "</option>";
        $html .= "</select>&nbsp;";
        $html .= "<select name='menuSize' class='select' onchange='JOSC_fontSize()'>";
        $html .= "<option>-" . _JOOMLACOMMENT_SIZE . "-</option>";
        $html .= "<option>" . _JOOMLACOMMENT_TINY . "</option>";
        $html .= "<option>" . _JOOMLACOMMENT_SMALL . "</option>";
        $html .= "<option>" . _JOOMLACOMMENT_MEDIUM . "</option>";
        $html .= "<option>" . _JOOMLACOMMENT_LARGE . "</option>";
        $html .= "<option>" . _JOOMLACOMMENT_HUGE . "</option>";
        $html .= "</select>";
        return $html;
    }

	function notifySelect() {    	
	    $html = '';
        $html .= "<select name='tnotify' class='inputbox'>";
		$html .= "<option ".($this->_tnotify ?  "" : "checked")	." >" 	. _JOOMLACOMMENT_ENTERNOTIFY0 	. "</option>";
		$html .= "<option ".($this->_tnotify ? "checked" : "")	." >" 	. _JOOMLACOMMENT_ENTERNOTIFY1	. "</option>";
        $html .= "</select>";
		return $html;
	}
	
    function form_htmlCode()
    {
        global $my, $gid;
        
        if (!$my->username && $this->_only_registered) return $this->onlyRegistered();

        $html = $this->_form;
        $html = ignoreBlock($html, 'UBBCode', (!$this->_support_UBBcode));
		$ignorecaptcha = !$this->_captcha; /* captcha already set according to usertypes */
        $html = ignoreBlock($html, 'captcha', $ignorecaptcha);

        if ($this->_support_UBBcode) {
            $UBBCodeButtons = $this->UBBCodeButtons();
            $UBBCodeSelect = $this->UBBCodeSelect();
            $html = str_replace('{_UBBCODE}', _JOOMLACOMMENT_UBBCODE, $html);
            $html = str_replace('{UBBCodeButtons}', $UBBCodeButtons, $html);
            $html = str_replace('{UBBCodeSelect}', $UBBCodeSelect, $html);
        }

        $html = str_replace('{_WRITECOMMENT}', _JOOMLACOMMENT_WRITECOMMENT, $html);
        $html = str_replace('{self}', 'index.php', $html);
        $html = str_replace('{id}', $this->_contentId, $html);
        
        $html = str_replace('{_ENTERNAME}', _JOOMLACOMMENT_ENTERNAME, $html);
        $html = str_replace('{username}', $this->_tname, $html);
        $html = str_replace('{registered_readonly}', $this->readOnly($this->_tname), $html);
        
        $html = str_replace('{email_display}', $this->displayStyle($this->_notify_users), $html);		
        $html = str_replace('{_ENTEREMAIL}', _JOOMLACOMMENT_ENTEREMAIL, $html);
        $html = str_replace('{email}', $this->_temail, $html);
        $html = str_replace('{notifyselect}', $this->notifySelect(), $html);
//        $html = str_replace('{_ENTERNOTIFY}', _JOOMLACOMMENT_ENTERNOTIFY, $html);
//        $html = str_replace('{notifycheck}', ($this->_tnotify ? "checked" : "") , $html);
        
        $html = str_replace('{_ENTERWEBSITE}', _JOOMLACOMMENT_ENTERWEBSITE, $html);
        $html = str_replace('{website}', $this->_twebsite, $html);

        $html = str_replace('{_ENTERTITLE}', _JOOMLACOMMENT_ENTERTITLE, $html);

        $html = str_replace('{emoticons}', $this->emoticons(), $html);
        $html = str_replace('{_SENDFORM}', _JOOMLACOMMENT_SENDFORM, $html);

       	$html = str_replace('{_CAPTCHATXT}', ($ignorecaptcha ? "" : _JOOMLACOMMENT_FORMVALIDATE_CAPTCHATXT ), $html);
        $html = str_replace('{security_image}', "<div id='captcha'>" . insertCaptcha('security_refid') . '</div>', $html);
        
        return $html;
    }
}

class search extends support {
    var $_search;
    var $_keyword;
    var $_phrase;
    var $_counter;
    var $_resultTemplate;

    function search($value)
    {
        $this->_search = $value;
    }

    function setKeyword($value)
    {
        $this->_keyword = addslashes(trim($value));
    }

    function setPhrase($value)
    {
        $this->_phrase = $value;
    }

    function anonymous($name)
    {
        if ($name == '') $name = filter($this->encodeData_Charset(_JOOMLACOMMENT_ANONYMOUS));
        return $name;
    }

    function searchMatch()
    {
        $result = ($this->_counter == 1) ? filter($this->encodeData_Charset(_JOOMLACOMMENT_SEARCHMATCH)) : filter($this->encodeData_Charset(_JOOMLACOMMENT_SEARCHMATCHES));
        return sprintf($result, $this->_counter);
    }

    function trimResult($html, $word, $size)
    {
        $html = str_replace("\n", '', $html);
        if ($word == '') return '';
        $p = strpos($html, $word);
        if ($p == 0) return substr($html, 0, $size);
        $len = strlen($html);
        $sublen = strlen($word);
        $size = ($size - $sublen) / 2;
        if ($size >= $len) $result = $html;
        else {
            if ($p < $size) $a = $p-1;
            else $a = $size;
            $c = $len - ($p + $sublen);
            if ($c < $size) $b = $c;
            else $b = $size;
            $b = $a + $b + $sublen;
            $result = substr($html, $p - $a, $b);
        }
        return $result;
    }

    function highlightWord($html, $maxSize = -1)
    {
        $html = stripslashes($html);
        if (($this->_phrase == 'any') Or ($this->_phrase == 'all')) {
            $words = split(' ', $this->_keyword);
            if ($maxSize != -1) $html = $this->trimResult($html, $words[0], $maxSize);
            foreach($words as $item) {
                if ($item != '')
                    $html = str_replace($item, "<span>$item</span>", $html);
            }
            return $html;
        } else {
            if ($maxSize != -1) $html = $this->trimResult($html, $this->_keyword, $maxSize);
            return str_replace($this->_keyword, "<span>$this->_keyword</span>", stripslashes($html));
        }
    }

    function addItem($item, $itemCSS)
    {
        $comment = $item['comment'];
        $title = $this->highlightWord($item['title']);
        $name = $this->highlightWord($this->anonymous($item['name']));
        $adress = 'javascript:JOSC_goToPost(' . $item['contentid'] . ',' . $item['id'] . ')';
        $maxsize = 200;
        if ($maxsize != 0 && strlen($comment) > $maxsize)
            $comment = '...' . $this->highlightWord($comment, $maxsize) . '...';
        else $comment = $this->highlightWord($comment);
        $html = $this->_resultTemplate;
        $html = str_replace('{postclass}', 'sectiontableentry' . $itemCSS, $html);
        $html = str_replace('{title}', "<b>$title</b>", $html);
        $html = str_replace('{_JOOMLACOMMENT_BY}', filter($this->encodeData_Charset(_JOOMLACOMMENT_BY)), $html);
        $html = str_replace('{name}', $name, $html);
        $html = str_replace('{adress}', $adress, $html);
        $html = str_replace('{preview}', $comment, $html);
        $html = str_replace('{date}', date($this->_date_format, strToTime($item['date'])), $html);
        return $html;
    }

    function find($terms)
    {
        global $database;
        $database->setQuery("SELECT * FROM #__comment WHERE $terms ORDER BY date DESC");
        $data = $database->loadAssocList();
        $html = '';
        $itemCSS = 1;
        $this->_counter = 0;
        if ($data == null) return '';
        foreach($data as $item) {
            $item = $this->filterAll($item);
            $html .= $this->addItem($item, $itemCSS);
            $this->_counter++;
            $itemCSS++;
            if ($itemCSS == 3) $itemCSS = 1;
        }
        return $html;
    }

    function terms($list, $term)
    {
        $result = '';
        foreach($list as $item) {
            if ($result != '') $result .= ' OR ';
            $result .= $item . " $term ";
        }
        return $result;
    }

    function anyWords($list)
    {
        $result = '';
        if (!strpos($this->_keyword, ' ')) return $this->terms($list, "LIKE '%$this->_keyword%'");
        $words = split(' ', $this->_keyword);
        foreach($words as $item) {
            if ($item != '') {
                if ($result != '') $result .= ' OR ';
                $result .= $this->terms($list, "LIKE '%$item%'");
            }
        }
        return $result;
    }

    function allWords($list)
    {
        $result = '';
        if (!strpos($this->_keyword, ' ')) return $this->terms($list, "LIKE '%$this->_keyword%'");
        $words = split(' ', $this->_keyword);
        foreach($words as $item) {
            if ($item != '') {
                if ($result != '') $result .= ' AND ';
                $result .= '(' . $this->terms($list, "LIKE '%$item%'") . ')';
            }
        }
        return $result;
    }

    function exactPhrase($list)
    {
        return $this->terms($list, "LIKE '%$this->_keyword%'");
    }

    function filterAll($item)
    {
	/*  ALSO IN BOARD CLASS
	 * 
	 */
        $item['name'] 	= filter($this->encodeData_Charset($item['name']));
        $item['title'] 	= filter($this->encodeData_Charset($item['title']));
        $item['comment'] = filter($this->encodeData_Charset($item['comment']));
/*        $item['name'] 	= filter($item['name']);
        $item['title'] 	= filter($item['title']);
        $item['comment'] = filter($item['comment']);*/
        return $item;
    }

    function decodeData_Charset($varName) {
	/*  ALSO IN BOARD CLASS
	 * javascript(ajax) encodeURI is only UTF-8. so we have to decode ajax send
	 * should be solved with joomla 1.5 ! (native utf-8)
	 */
	 if ($this->_ajax)
        return myiconv_decode( decodeData($varName), $this->_local_charset );
     else
     	return decodeData($varName);    	
    }
    
    function encodeData_Charset($var) {
	/*  ALSO IN BOARD CLASS
	 *  javascript(ajax) encodeURI is only UTF-8. so we have to decode ajax send
	 * should be solved with joomla 1.5 ! (native utf-8)
	 */
	 if ($this->_ajax)
        return myiconv_encode( $var , $this->_local_charset );
     else
     	return $var;  	        
    }
       
    function search_htmlCode()
    {
        $html = $this->_search;
        if ($this->_keyword) {
            $list[] = 'name';
            $list[] = 'title';
            $list[] = 'comment';
            if ($this->_phrase == 'any') $terms = $this->anyWords($list);
            if ($this->_phrase == 'all') $terms = $this->allWords($list);
            if ($this->_phrase == 'exact') $terms = $this->exactPhrase($list);
            $this->_resultTemplate = block($html, 'searchresult');
            $results = $this->find($terms);
        } else $results = '';
        $html = str_replace('{resulttitle}', ($results) ? $this->searchMatch() : filter($this->encodeData_Charset(_JOOMLACOMMENT_NOSEARCHMATCH)), $html);
        $html = ignoreBlock($html, 'searchresult', true, $results);
        return $html;
    }
}

?>
